package com.sany.boot.influxdb;

import org.influxdb.InfluxDB;
import org.influxdb.InfluxDBFactory;
import org.influxdb.dto.Query;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
@ConditionalOnClass(InfluxDB.class)
@EnableConfigurationProperties(InfluxdbProperties.class)
public class InfluxdbAutoConfiguration {

    Logger logger = LoggerFactory.getLogger(InfluxdbAutoConfiguration.class);


    @Autowired
    private InfluxdbProperties influxdbProperties;

    @Bean
    @ConditionalOnMissingBean
    public InfluxDB influxDB() {

        InfluxDB influxDB = InfluxDBFactory.connect(influxdbProperties.getUrl(), influxdbProperties.getUsername(), influxdbProperties.getPassword());
        try {
            influxDB.query(new Query("CREATE DATABASE " + influxdbProperties.getDatabase()));
            influxDB.setDatabase(influxdbProperties.getDatabase());
        } catch (Exception e) {
            logger.error("create influx db failed, error: {}", e.getMessage());
        } finally {
            influxDB.setRetentionPolicy(influxdbProperties.getRetentionPolicy());
        }
        influxDB.setLogLevel(influxdbProperties.getLogLevel());
        return influxDB;
    }

}
